﻿package com.thorqq.magictimer.widget;

import java.util.ArrayList;

import com.thorqq.magictimer.util.Util;

import android.content.Context;
import android.database.DataSetObserver;
import android.graphics.Canvas;
import android.graphics.Rect;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.LinearLayout;

public class GridViewWithDivider extends LinearLayout
{
    class GridViewAdapterDataSetObserver extends DataSetObserver
    {
        @Override
        public void onChanged()
        {
            mView.updateView();
        }

        @Override
        public void onInvalidated()
        {
            mView.updateView();
        }

        public void setView(GridViewWithDivider v)
        {
            mView = v;
        }

        GridViewWithDivider mView;
    }

    private BaseAdapter mAdapter;
    private OnClickListener onClickListener = null;
    GridViewAdapterDataSetObserver mDataSetObserver;

    private Drawable mHorizontalDivider;
    private Drawable mVerticalDivider;

    private int mHorizontalDividerHeight;
    private int mVerticalDividerWidth;

    private boolean mHorizontalClipDivider;
    private boolean mVerticalClipDivider;

    // private int mRow;
    private int mColumn;

    private View mHeaderView;
    private View mFooterView;

    private ArrayList<View> mCacheView = new ArrayList<View>();
    private ArrayList<LinearLayout> mCacheRow = new ArrayList<LinearLayout>();
    // private ArrayList<LinearLayout> mLinearLayoutRow = new
    // ArrayList<LinearLayout>();
    private int[] mVerticalDividerPos;
    private int[] mChildViewWidth;

    public void fillLinearLayout()
    {
        removeAllViews();

        // 头
        if (mHeaderView != null)
        {
            addView(mHeaderView);
        }

        // 计算行数
        int count = mAdapter.getCount();
        int row = 0;
        if (mColumn <= 0)
        {
            return;
        } else
        {
            row = count / mColumn;
            row += (count % mColumn == 0 ? 0 : 1);
        }

        // TODO 判断是否要清楚缓冲区。全部清掉,太粗暴了
        if (mCacheView.size() != count)
        {
            mCacheView.clear();
            mCacheRow.clear();
        }

        for (int i = 0; i < count; i++)
        {
            int y = i / mColumn;
            int x = i % mColumn;

            View srcView = null;

            // 从缓冲中获取view
            if (i < mCacheView.size())
            {
                // srcView = mCacheRow.get(row).getChildAt(column);
                srcView = mCacheView.get(i);
            }

            View v = mAdapter.getView(i, srcView, null);
            v.setClickable(true);
            v.setFocusable(true);

            // 行数不够，增加一行
            if (y >= mCacheRow.size())
            {
                LinearLayout layout = new LinearLayout(getContext());
                layout.setOrientation(LinearLayout.HORIZONTAL);
                layout.setWeightSum(1.0f);
                mCacheRow.add(layout);

            }
            


            // 加入缓冲
            if (mCacheView.size() <= i)
            {
                mCacheView.add(v);
                mCacheRow.get(y).addView(v);
            }

            // 设置监听器
            if(this.onClickListener != null)
            {
                Util.log("v.setOnClickListener");
                v.setOnClickListener(this.onClickListener);
            }

            // com.thorqq.magictimer.util.Util.log("i / mRow = " + i / mRow);
            // 添加一行子布局到总布局
            if (x == 0)
            {
                addView(mCacheRow.get(y));
            }

        }

        if (mFooterView != null)
        {
            addView(mFooterView);
        }

    }

    public void updateView()
    {
        fillLinearLayout();
    }

    public GridViewWithDivider(Context context)
    {
        super(context);
    }

    public GridViewWithDivider(Context context, AttributeSet attrs)
    {
        super(context, attrs);
    }

    public android.widget.BaseAdapter getAdpater()
    {
        return mAdapter;
    }

    public void setColumnNum(int column)
    {
        mColumn = column;
        mVerticalDividerPos = new int[mColumn + 1];
        mChildViewWidth = new int[mColumn];
    }

    public void setAdapter(android.widget.BaseAdapter adpater)
    {
        this.mAdapter = adpater;

        mDataSetObserver = new GridViewAdapterDataSetObserver();
        adpater.registerDataSetObserver(mDataSetObserver);
        mDataSetObserver.setView(this);

        fillLinearLayout();
    }

    public OnClickListener getOnclickListner()
    {
        return onClickListener;
    }

    public void setOnclickLinstener(OnClickListener onClickListener)
    {
        this.onClickListener = onClickListener;
    }

    public void addFooterView(View v)
    {
        mFooterView = v;
    }

    public void addHeaderView(View v)
    {
        mHeaderView = v;
    }

    public void setHorizontalDivider(Drawable divider)
    {

        if (divider != null)
        {
            mHorizontalDividerHeight = divider.getIntrinsicHeight();
            mHorizontalClipDivider = divider instanceof ColorDrawable;
        } else
        {
            mHorizontalDividerHeight = 0;
            mHorizontalClipDivider = false;
        }

        mHorizontalDivider = divider;
    }

    public void setVerticalDivider(Drawable divider)
    {

        if (divider != null)
        {
            mVerticalDividerWidth = divider.getIntrinsicHeight();
            mVerticalClipDivider = divider instanceof ColorDrawable;
        } else
        {
            mVerticalDividerWidth = 0;
            mVerticalClipDivider = false;
        }

        mVerticalDivider = divider;
    }

    public void setHorizontalDividerHeight(int height)
    {
        mHorizontalDividerHeight = height;
    }

    public void setVerticalDividerWidth(int width)
    {
        mVerticalDividerWidth = width;
    }

    private void drawDivider(Canvas canvas, Rect bounds, Drawable divider, boolean clipDivider)
    {
        // This widget draws the same divider for all children
        if (!clipDivider)
        {
            divider.setBounds(bounds);
        } else
        {
            canvas.save();
            canvas.clipRect(bounds);
        }

        divider.draw(canvas);

        if (clipDivider)
        {
            canvas.restore();
        }
    }

    private void drawVerticalDivider(Canvas canvas, Rect bounds)
    {
        drawDivider(canvas, bounds, mVerticalDivider, mVerticalClipDivider);
    }

    private void drawHorizontalDivider(Canvas canvas, Rect bounds)
    {
        drawDivider(canvas, bounds, mHorizontalDivider, mHorizontalClipDivider);
    }

    private void calculateVerticalDividerPos(int width)
    {
        // 各个分隔线的位置
        for (int i = 0; i < mColumn; i++)
        {
            mVerticalDividerPos[i] = (int) (width * 1.0 * i / mColumn);
        }
        mVerticalDividerPos[mColumn] = width - mVerticalDividerWidth;

        // 子视图的宽度
        for (int i = 0; i < mColumn; i++)
        {
            mChildViewWidth[i] = mVerticalDividerPos[i + 1] - mVerticalDividerPos[i];
        }
    }
    
    private void resetChildViewWidth()
    {
        for (int i = 0; i < super.getChildCount(); i++)
        {
            ViewGroup vg = (ViewGroup) super.getChildAt(i);
            for (int j = 0; j < vg.getChildCount(); j++)
            {
                View v = vg.getChildAt(j);
                v.setLayoutParams(new LinearLayout.LayoutParams(mChildViewWidth[j],LayoutParams.WRAP_CONTENT));    
            }
        }
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec)
    {
        // 计算垂直分隔线的位置和子视图的宽度
        calculateVerticalDividerPos(MeasureSpec.getSize(widthMeasureSpec));
        resetChildViewWidth();
        
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    }

    @Override
    protected void dispatchDraw(Canvas canvas)
    {
        super.dispatchDraw(canvas);

        // Draw the indicators (these should be drawn above the dividers) and
        // children
        // 没有内容，无需画线
        if (super.getChildCount() <= 0)
        {
            return;
        }

        int count = mAdapter.getCount();
        int row = count / mColumn;
        row += (count % mColumn == 0 ? 0 : 1);

        // 画水平分隔线
        if (mHorizontalDividerHeight > 0 && mHorizontalDivider != null)
        {
            final Rect bounds = new Rect();

            bounds.left = getPaddingLeft();
            bounds.right = getRight() - getLeft() - getPaddingRight();

            int bottom;
            int top;
            int gridBottom = getBottom() - getTop() - getPaddingBottom();

            for (int i = 0; i < row; i++)
            {
                View child = getChildAt(i);

                top = child.getTop();
                bottom = child.getBottom();

                // 每一行的上面的分隔线
                if (top <= gridBottom)
                {
                    bounds.top = top;
                    bounds.bottom = top + mHorizontalDividerHeight;
                    drawHorizontalDivider(canvas, bounds);
                }

                // 最后一行的下面的分隔线
                if (i == row - 1)
                {
                    bounds.top = bottom - mHorizontalDividerHeight;
                    bounds.bottom = bottom;
                    drawHorizontalDivider(canvas, bounds);
                }
            }
        }

        // 画垂直分隔线
        if (mVerticalDividerWidth > 0 && mVerticalDivider != null)
        {
            final Rect rect = new Rect();
            rect.top = getPaddingTop();
            rect.bottom = getBottom() - getTop() - getPaddingBottom();

            // 画线
            for (int i = 0; i <= mColumn; i++)
            {
                rect.left = mVerticalDividerPos[i];
                rect.right = mVerticalDividerPos[i] + mVerticalDividerWidth;
                drawVerticalDivider(canvas, rect);
            }
        }

    }

}
